﻿var yuZoomImages = new HashMap(); //全局的图片存储
var nullPic = "/js/yu_zoom/images/transparent.gif";

var MyYuZoom = function(option){
	//图片缓存表
	
	//任务队列
	var tasks = new TaskQueue();
	
	//运行状态
	var state = {
		//应用ID
		id : null,
		
		//组件背景样式
		background : '#EEE',
		
		//配置文件路径
		configUrl : null,
		
		//图片基本路径
		path : null,
		
		//旋转角度数
		count : 0,
		
		//容器
		content: null,
		
		//最大放大倍数
		maxZoom : 1,
		
		//当前旋转系数
		clockwiseLevel : 0,
		
		//起始系数，指clockwiseLevel对应的图片名
		startInit : 0,
		
		//X轴(焦点/可视范围在图片的中心点)
		x : 0,
		
		//Y轴
		y : 0,
		
		//缩略图宽范围
		maxThumbW : 200,
		
		//缩略图范围
		maxThumbH : 200,
		
		//文件类型
		imgType : '.jpg',
		
		//缩略图缩小比例(为精确，使用double型)
		thumbRate : 4,
		
		//是否正在移动导航图
		guild : false,
		
		//原始图片宽
		srcW : 0,
		
		//原始图片高
		srcH : 0,
		
		//缩略图位置[bottom | top | left | right]
		thumbPosition : 'top', 
		
		//缩略图是否显示
		thumbShow : false, 
		
		//组件宽
		yuW : 0, 
		
		//组件高
		yuH : 0, 
		
		//是否反向（转动）
		revert : false,
		
		//是否全屏
		fullScream : false, 
		
		//工具栏是否显示
		toolsShow : true, 
		
		//工具栏位置[bottom | top | left | right]
		toolsPosition : 'bottom', 
		
		//是否正在忙
		busy : false,
		
		//当前鼠标事件：0 转动，1 移动，2 选择
		curMouseAct : 0,
		
		//切割小图的宽度
		picW : 500,
		
		//切割小图的高度
		picH : 500,
		
		//当前任务数
		processCount : 0,
		
		//是否加载完毕
		loaded : false,
		
		//事件数组，加载完成时执行
		onload : [],
		
		//当前事件： 3d / move / zoom 
		action : '3d',
		
		//默认转动速度
		defaultTurnSpeed : 80,
		
		//鼠标位置
		snapshot : {},
		
		//最大可旋转放大倍数，越过此倍数后，不再支持旋转而直接转成移动
		maxClockwiseZoom : 1
	};
	
	//初始化
	state.zoomLevel = 1;
	
	var baseState = copyYuState(state);//复制一份作为备份，在重新设置实例时使用
	
	/**
	 * 放大（选择框触发的放大）
	 * @param x 开始x坐标
	 * @param y 开始y坐标
	 * @param width 宽
	 * @param height 高
	 * @param params = {
		 	x : int,	//(x,y) 放大中心的坐标（以组件左上角为原点）
			y : int,
			zoom : int([0,maxZoom]), //放大倍数
			callback : function,	//回调函数
		 }
	 */
	this.zoom = function(params){
		var zoom = params.zoom;
		var x,y;
		if(params.x){
			x = params.x;
		}else{
			x = state.yuW / 2;
		}
		if(params.y){
			y = params.y;
		}else{
			y = state.yuH / 2;
		}
		zoomTo(zoom > state.zoomLevel, zoom, params.callback, x, y);
	};
	
	/*
	 * 收缩到
	 */
	var zoomTo = function(zoomin, zoom, fun, x, y){
		if(state.zoomLevel == zoom){
			if(fun)fun();
			return;
		}
		if(zoomin){
			//放大
			yuZoomObj.zoomIn(function(){
				zoomTo(zoomin, zoom, fun);
			},x,y);
		}else{
			//缩小
			yuZoomObj.zoomOut(function(){
				zoomTo(zoomin, zoom, fun);
			},x,y);
		}
	};
	
	/**
	 * 放大
	 * @param (x,y) 放大中心的坐标（以组件左上角为原点）
	 */
	this.zoomIn = function(fun, x, y){
		if(state.zoomLevel == state.maxZoom)return;
		//中断可能在进行的动作
		state.processCount=0;
		
		if(x==null) x = state.yuW / 2;
		if(y==null) y = state.yuH / 2;
		
		state.x = 2*state.x - x;
		state.y = 2*state.y - y;
		
		++state.zoomLevel;
		
		setZoomDir(true, fun);
	};
	
	/**
	 * 缩小
	 */
	this.zoomOut = function(fun, x, y){
		if(state.zoomLevel == 1)return;
		
		//中断可能在进行的动作
		state.processCount=0;
		
		if(x==null) x = state.yuW / 2;
		if(y==null) y = state.yuH / 2;
		
		state.x = (x + state.x) / 2;
		state.y = (y + state.y) / 2;
		
		--state.zoomLevel;
		//计算边界
		x_y_limit();
		
		setZoomDir(false,fun);
	};
	
	var setZoomDir = function(is_zoomIn,fun){
		//if(hi[2][1]!=yuZoomKey[3]){yuZoomObj = {};return;}//验证
		x_y_limit();
		
		//设置导航条
		$(state.yuYCID + " .zoomKD span").css({bottom:(state.zoomLevel-1)*8});
		
		var rate = Math.pow(2, state.zoomLevel-1);
		var w1 = state.srcW * rate;
		var h1 = state.srcH * rate;
		state.w1 = w1;
		state.h1 = h1;
		
		if(is_zoomIn){
			if(state.zoomLevel > state.maxClockwiseZoom && state.action != 'move'){
				//如果当前放大倍数超过预定值且当前动作不为移动时，切换成移动
				yuZoomObj.setAction('move');
			}
		}else{			
			if(w1<=state.yuW && h1<=state.yuH && state.zoomLevel <= state.maxClockwiseZoom){
				//禁止移动
				yuZoomObj.setAction('3d');
			}
		}
		//基层放大一倍（包括图片）,x向左移动 (zoomLevel + 1)*srcW/2，y向上移动(zoomLevel + 1)*srcH/2
		$(state.yuYCID + " .picsDiv").html("").css({left:state.x,top:state.y,width:w1,height:h1}).show();
		
		
		var clockwise_id = "#clockwise_" + state.id + state.clockwiseLevel;
		$(state.yuYCID + " .clockwise_1").dequeue().animate({left:state.x,top:state.y,width : w1, height : h1},{
			step : function(now, fx){
				if(fx.prop == 'height'){
					$(clockwise_id).css({height : now});
				}else if(fx.prop == 'width'){
					$(clockwise_id).css({width : now});
				}
			},
			duration : 1000,
			complete : function(){
					var p_w = $(this).width();
					var p_h = $(this).height();
				$(state.yuYCID + " .clockwise_1 img").css({width:p_w,height:p_h});
				if(2 >= state.zoomLevel){
					//小于允许转动的值时，加载全图
					var key = state.id + '_' + state.zoomLevel + '_' + state.clockwiseLevel;
					var img = yuZoomImages.get(key);
					if(img == null){
						var serials = state.serials;
						var src = state.path + "/"+serials[state.zoomLevel] + "_"+serials[state.clockwiseLevel] + state.imgType;						
						if(isIE){
							src+= "?t=" + Math.random();
						}
						
						loadImg(key, src, function(img){
							$(clockwise_id).attr("src", img.src);
						});
					}else{
						$(clockwise_id).attr("src", img.src);
					}
				}else{
					//否则加载切片
					load_view_image();
				}
				if(fun)fun();
			}
		});
		
		//生成放大层网格
		createPicDiv();
		init_thumb();
	};
	
	/**
	 * 设置当前事件
	 */
	this.setAction = function(act){
		//添加加密
		//if(hi[1][1]!=yuZoomKey[2]){yuZoomObj = {};return;}
		
		switch(act){
			case '3d':
				state.action='3d';
				$(state.yuYCID).css("cursor", "ew-resize");
				$(state.yuYCID + " " + state.yuZoomToolsYClass + " .selected").removeClass("selected");
				$(state.yuYCID + " " + state.yuZoomToolsYClass + " .handle_3d").addClass("selected");
				break;
			case 'move':
				state.action='move';
				$(state.yuYCID).css("cursor", "move");
				$(state.yuYCID + " " + state.yuZoomToolsYClass + " .selected").removeClass("selected");
				$(state.yuYCID + " " + state.yuZoomToolsYClass + " .handle_move").addClass("selected");
				break;
				
		}
	};
	
	var createPicDiv = function(){
		//创建新的图层
		var rate = Math.pow(2, state.zoomLevel - 1);
		var w = state.srcW * rate;
		var h = state.srcH * rate;
		var w1 = w, h1 = h;
		//清除放大层内容
		if(state.zoomLevel == 1)return;
		var j = 0;
		while(true){
			var i = 0;
			w1 = w;
			var j_end = h1 < state.picH;
			while(true){
				var i_end = w1 < state.picW;
				var style = "";
				if(i_end) style += "width:" + w1 + "px;";
				if(j_end) style += "height:" + h1 + "px;";
				if(style != ""){
					style = ' style="' + style + '"';
				}
				//var src = state.path + "/"+state.zoomLevel + "/"+state.clockwiseLevel + "/" + j + "_" + i + ".jpg";
				var clazz = "i_" + j + "_" + i;
				$(state.yuYCID + " .picsDiv").append('<img src="'+nullPic+'"' + style + ' class="'+clazz+'"/>');
				
				++i;
				w1 -= state.picW;
				if(w1 < 0)break;
			}
			
			++j;
			h1 -= state.picH;
			if(h1 < 0)break;
		}
	};
	
	/**
	 * @param fun 回调函数，即load_view_image执行完后的回调
	 * 无法控制最后一个加载图片返回与本回调之间的先后顺序，所以要小心使用
	 */
	var load_view_image = function(fun){
		if(state.zoomLevel < 2){return}
		var x1 = Math.ceil(-state.x / state.picW) - 1; //x轴从第几块开始计
		if(x1<0) x1 = 0;
		
		var y1 = Math.ceil(-state.y / state.picH) - 1; //y轴从第几块开始计
		if(y1<0) y1 = 0;
		var c1 = Math.ceil(((-state.x % state.picW) + state.yuW) / state.picW); //x轴连续几块
		var r1 = Math.ceil(((-state.y % state.picH) + state.yuH) / state.picH); //y轴连续几块
		
		var proc_count = 0;
		//var cc = 0;
		for(k=0;k<c1;++k){
			for(l=0;l<r1;++l){
				var clazz = "i_" + (y1 + l) + "_" + (x1 + k);
				++proc_count;
				//$("#yu"+state.id+" .picsDiv img:eq("+cc+")").attr("class",clazz);
				//++cc;
				var key = state.id + '_' + state.zoomLevel + '_' + state.clockwiseLevel + '_' + (y1 + l) + "_" + (x1 + k);
				var img = yuZoomImages.get(key);
				var serials = state.serials;
				if( img == null){
					var src = null;
					if(state.zoomLevel < 2){
						console.log('------------->' + state.clockwiseLevel);
					}

						src = state.path + "/"+serials[state.zoomLevel] + "_"+serials[state.clockwiseLevel] + "_" + serials[(y1 + l)] + "_" + serials[(x1 + k)] + state.imgType;					
					// }else{
					// 	src = state.path + "/"+serials[state.zoomLevel] + "_"+serials[state.clockwiseLevel] + state.imgType;
					// }
					
					if(isIE){
						src+= "?t=" + Math.random();
					}
					
					tasks.addTask({
						src : src,
						clazz : clazz,
						zoom : state.zoomLevel,
						clockwise : state.clockwiseLevel,
						x : x1 + k,
						y : y1 + l,
						key : key,
						run : function(callback){
							//加载图片
							var img = new Image();
							img.src = this.src;
							var zoom = this.zoom;
							var clockwise = this.clockwise;
							var key = this.key;//state.id +  '_' + this.clockwise + '_' + this.y + "_" + this.x;
							//img.key = key;
							var clazz = this.clazz;
							$(img).load(function(){
								if(this.height>0){
									yuZoomImages.put(key,img);
								}
								if(zoom == state.zoomLevel && clockwise == state.clockwiseLevel)
									$(state.yuYCID + " ." + clazz).attr("src",this.src);
							});
							--proc_count;
							if(callback)callback();
							if(proc_count == 0 && fun)fun();
						},
						validate : function(){
							return  true;//!yuZoomImages.containsKey(key);
						}
					});
				}else{
					$(state.yuYCID + " ." + clazz).attr("src",img.src);
					--proc_count;
					if(proc_count == 0 && fun)fun();
				}
			}
		}
	};
	
	var reset_view_image = function(fun){
		var x1 = Math.ceil(-state.x / state.picW) - 1; //x轴从第几块开始计
		if(x1<0) x1 = 0;
		
		var y1 = Math.ceil(-state.y / state.picH) - 1; //y轴从第几块开始计
		if(y1<0) y1 = 0;
		var c1 = Math.ceil(((-state.x % state.picW) + state.yuW) / state.picW); //x轴连续几块
		var r1 = Math.ceil(((-state.y % state.picH) + state.yuH) / state.picH); //y轴连续几块
		
		//var cc = 0;
		for(k=0;k<c1;++k){
			for(l=0;l<r1;++l){
				var clazz = "i_" + (y1 + l) + "_" + (x1 + k);
				$(state.yuYCID + " ." + clazz).attr("src",nullPic);
			}
		}
	};
	
	/**
	 * 移动，偏移量为：(x,y)
	 */
	this.move = function(x, y){
		if(state.guild){
			var rate = Math.pow(2,state.zoomLevel-1);
			x = -x * rate * state.srcW / state.thumbW;
			y = -y * rate * state.srcH / state.thumbH;
		}
		state.x+=x;
		state.y+=y;
		//计算边界
		x_y_limit();
		
		//移动
		$(state.yuYCID+" .clockwise_1,"+state.yuYCID+" .picsDiv").css({left:state.x, top:state.y});
		load_view_image();
		if(!state.guild)
			init_thumb();
	};
	
	/**
	 * 设置大小（宽，高）
	 */
	this.setSize = function(width, height){
		
	};
	
	/**
	 * 转动
	 * @param clockwise 偏移量，整数。正数顺时针（俯视），负数逆时针
	 */
	this.turn = function(clockwise, fun){
		if(clockwise == 0){
			if(fun)fun();
			return;
		}else if(clockwise>0){
			state.processCount = clockwise;
			autoPlayStart(state.defaultTurnSpeed, state.clockwiseLevel, false, fun);
		}else{
			state.processCount = -clockwise;
			autoPlayStart(state.defaultTurnSpeed, state.clockwiseLevel, true, fun);
		}
	};
	
	/**
	 * 获取本类的状态，以便外部控制
	 */
	this.getState = function(){return state;};
	
	/**
	 * 转动
	 * @param clockwiseLevel 转动到某点。正数为顺时针（俯视），负数逆时针
	 */
	this.turnTo = function(clockwiseLevel, fun){
		if(state.clockwiseLevel == clockwiseLevel)return;
		
		//隐藏原角度层
		$("#clockwise_" + state.id + state.clockwiseLevel).hide();
		state.clockwiseLevel = clockwiseLevel;
		var clockwise_id = "#clockwise_" + state.id + clockwiseLevel;
		//修改显示层宽高
		$(clockwise_id).css({display : 'block'});
		
		if(!state.ondrag)
			$(state.yuYCID + " .picsDiv").show();
		
		if(2 >= state.zoomLevel){
			//小于允许转动的值时，加载全图
			var key = state.id + '_' + state.zoomLevel + '_' + state.clockwiseLevel;
			var img = yuZoomImages.get(key);
			if(img == null){
				var serials = state.serials;
				var src = state.path + "/"+serials[state.zoomLevel] + "_"+serials[state.clockwiseLevel] + state.imgType;
				if(isIE){
					src+= "?t=" + Math.random();
				}
				
				loadImg(key, src, function(img){
					$(clockwise_id).attr("src", img.src);
					if(fun)fun();
				});
			}else{
				$(clockwise_id).attr("src", img.src);
				if(fun)fun();
			}
			//隐藏切片层
			$(state.yuYCID+" .picsDiv").hide();
		}else if(!state.busy && !state.ondrag){
			//否则加载切片
			//$(state.yuYCID+" .picsDiv").hide();
			//document.title = clockwiseLevel + "_" + Math.random();
			//load_view_image(fun);
		}
		init_thumb();
		
		//更改滑块
		changeSlider();
	};
	
	var changeSlider = function(){
		var sl = parseInt(state.yuW/2*( 1 - state.clockwiseLevel/state.count));
		$(state.yuYCID + " .slider").css({left : sl});
	};
	
	/**
	 * 全屏
	 */
	this.fullScreen = function(){
		var w = $(window).width();
		var h = $(window).height();
		$(state.yuYCID).appendTo("body");
		state.yuH = h;
		state.yuW = w;
		var yu_position = isIE6?'absolute':'fixed';
		$(state.yuYCID).css({position:yu_position}).add(state.yuYCID+" .mb").dequeue().animate({top:0,left:0,width:w,height:h},function(){
			//提示退出方法
			if(!$(state.yuYCID + " .yu_tips").length){
				$(state.yuYCID).append('<div class="yu_tips"><div class="yu_tips_bg"></div><p>'+language.yu_tips+'</p></div>');
				setTimeout(function(){$(state.yuYCID + " .yu_tips").fadeOut(function(){$(this).remove()})},3000);
			}		
			
			yuZoomObj.move(0,0);
			state.fullScream = true;
			
			init_thumb();
			changeSlider();
		});
		
		//更改窗体后修改
		//window.resize = yuZoomObj.fullScreen;
		//隐藏按钮
		$(state.yuYCID+" .handle_fullscreen").hide();
		
		//显示退出按钮
		$(state.yuYCID+" .handle_exitfullscreen").show(function(){$(this).css({display: 'inline-block'})});
	};
	
	/**
	 * 从全屏中还原
	 */
	this.resetScreen = function(){
		var w = $(state.content).width();
		var h = $(state.content).height();
		$(state.yuYCID).appendTo(state.content);
		state.yuH = h;
		state.yuW = w;
		$(state.yuYCID+","+state.yuYCID+" .mb").css({position:'relative',width:w,height:h});
		yuZoomObj.move(0,0);
		state.fullScream = false;
		init_thumb();
		changeSlider();
		
		//隐藏提示框，如果快速点击全屏、还原时
		$(state.yuYCID + " .yu_tips").fadeOut(function(){$(this).remove()});
		
		//$(document).unbind("resize");
		//隐藏退出按钮
		$(state.yuYCID+" .handle_exitfullscreen").hide();
		
		//显示按钮
		$(state.yuYCID+" .handle_fullscreen").show(function(){$(this).css({display: 'inline-block'})});
	};
	
	/**
	 * 显示缩略图
	 * @param position 位置:0 左上，1 右上，2 右下，3 左下
	 */
	this.showThumb = function(position){
		
	};
	
	/**
	 * 隐藏缩略图
	 */
	this.hideThumb = function(){
		
	};
	
	/**
	 * 设置缩略图大小
	 * @param width 宽
	 * @param height 高
	 */
	this.setThumbSize = function(width, height){
		
	};
	
	/**
	 * 选择框选择
	 * @param x 开始x坐标
	 * @param y 开始y坐标
	 * @param width 宽
	 * @param height 高
	 */
	this.selectDict = function(x, y, width, height){
		
	};
	
	/**
	 * 显示工具条
	 * @param position 位置:0 左上，1 右上，2 右下，3 左下
	 */
	this.showTools = function(position){
		
	};
	
	/**
	 * 隐藏工具条
	 */
	this.hideTools = function(){
		
	};
	
	var autoPlayStart = function(speed, clockwise, is_revert, fun){
		if(state.zoomLevel != 1){
			var tempProcessCount = state.processCount;
			yuZoomObj.zoom({
				zoom : 1,
				callback : function(){
					state.processCount = tempProcessCount;
					playStart(speed, clockwise, is_revert, fun);
				}
			});
		}else{
			playStart(speed, clockwise, is_revert, fun);
		}
	};
	
	var playStart = function(speed, clockwise, is_revert, fun){
		if(state.processCount == 0){
			//执行完毕
			state.busy = false;
			if(fun)fun();
			return;
		}
		
		if(is_revert==null)
			is_revert = state.revert;
		
		--state.processCount;
		if(is_revert){
			--clockwise;
		}else{
			++clockwise;
		}
		
		clockwise = getClockwise(clockwise);
		yuZoomObj.turnTo(clockwise);
		
		setTimeout(function(){playStart(speed, clockwise, is_revert, fun)},speed);
		
	};
	
	/**
	 * 自动旋转
	 * @param speed 速度
	 * @param count 旋转多少圈，默认为1
	 * @param fun 回调函数，可选，表示旋转完后执行的函数
	 */
	this.autoPlay = function(config){
		if(!state.loaded){
			//如果还没有加载完，则加入加载完事件中
			state.onload[state.onload.length] = function(){
				yuZoomObj.autoPlay(config);
			};
			return;
		}
		if(config == null)return;
		var speed = config.speed==null?state.defaultTurnSpeed:config.speed;
		var count = config.count == null?1:config.count;
		var revert = config.revert==null?state.revert:config.revert;
		var fun = config.callback == null?function(){}:config.callback;
		//刚进来时，以0点开始
		if(state.busy)
			return;
		state.busy = true;
		
		//验证
		//if(hi[0][0]!=yuZoomKey[1]){yuZoomObj = {};return;}
		
		//初始化任务
		state.processCount = state.count * count;
		autoPlayStart(speed, state.clockwiseLevel, revert, fun);
	};
	
	this.stopPlay = function(){
		
	};
	
	/**
	 * 更改图片（换成另一组），如果切换成功，则返回true,否则返回false
	 */
	this.change = function(configure){
		if(state.busy){
			return false;
		}
		$(state.yuYCID).remove();
		state = copyYuState(baseState);
		init(configure);
		return true;
	};
	
	//------------------------------------------以下为私有方法
	
	var x_y_limit = function(){
		var changed = false;
		var rate = Math.pow(2, state.zoomLevel-1);
		var w1 = state.srcW * rate;
		var h1 = state.srcH * rate;
		if(state.x>0){
			state.x = 0;
			changed = true;
		}else if(w1+state.x<state.yuW){
			state.x = state.yuW-w1;
			changed = true;
		}
			
		if(state.y>0){
			state.y = 0;
			changed = true;
		}else if(h1+state.y<state.yuH){
			state.y = state.yuH-h1;
			changed = true;
		}
		
		//如果边界都在里面，则居中
		if(w1 < state.yuW){
			state.x = parseInt((state.yuW - w1)/2);
			changed = true;
		}
		if(h1 < state.yuH){
			state.y = parseInt((state.yuH - h1)/2);
			changed = true;
		}
		return changed; 
	};
	
	/**
	 * 加载服务器配置文件
	 * @param callbackFun 回调函数
	 */
	var loadConfig = function(callbackFun){
		if(callbackFun){
			state.onload[state.onload.length] = callbackFun;
		}
		if(state.configUrl.indexOf("?")!=-1){
			state.configUrl += "&t=" + Math.random();
		}else{
			state.configUrl += "?t=" + Math.random();
		}
		state.configUrl += "&key=" + yuZoomKey+"&callback=?";
		$.getJSON(state.configUrl, function(yuJsonConfig){
			// console.log(yuJsonConfig);
			//var str = d(json.config,hi[0], hi[1], 's');
			//var yuJsonConfig = getJSON(str);
			if(!yuJsonConfig.st){
				alert("ERROR:" + yuJsonConfig.info);
				return;
			}
			//处理serials 
			
			if(yuJsonConfig.serials.indexOf(",") >= 0){
				state.serials = yuJsonConfig.serials.split(",");
			}else{
				state.serials = [];
				for(j=0,cc=yuJsonConfig.serials.length/2;j<cc;++j){
					state.serials[j] = yuJsonConfig.serials.substring(2*j, 2*j + 2);
				}
			}
			state.reserials = [];
			for(i=0,c=state.serials.length;i<c;++i){
				state.reserials[state.serials[i]] = i;
			}
			
			state.path 				= yuJsonConfig.path;
			state.count 			= yuJsonConfig.count;
			state.maxZoom 			= yuJsonConfig.maxZoom;
			state.zoomLevel 		= yuJsonConfig.defaultZoomLevel;
			state.w1 = state.srcW 	= yuJsonConfig.srcW;
			state.h1 = state.srcH 	= yuJsonConfig.srcH;
			
			if(yuJsonConfig.maxClockwiseZoom){
//				state.maxClockwiseZoom = yuJsonConfig.maxClockwiseZoom;
				state.maxClockwiseZoom = yuJsonConfig.maxClockwiseZoom;
			}
		
			if(yuJsonConfig.revert){
				state.revert = yuJsonConfig.revert;
			}
			
			if(yuJsonConfig.imgType){
				state.imgType = '.' + yuJsonConfig.imgType;
			}
			
			//2D 
			if(state.count == 1){
				$(state.yuYCID).find(".handle_3d,.handle_reset,.slider_content").hide();
			}
			
			//初始化x,y
			state.x = -(state.srcW - state.yuW)/2;
			state.y = -(state.srcH - state.yuH)/2;
			//初始化位置
			$(state.yuYCID + " .clockwise_1").css({left:state.x,top:state.y});
			
			$(state.yuYCID + " .zoomKD").css({height:state.maxZoom * 8}).parent().show();
			$(state.yuYCID + " .zoomKD span").css({bottom:(state.zoomLevel - 1) * 8});
			 
			 //初始化底层宽高
			 $(state.yuYCID + " .clockwise_1").css({width:state.srcW, height:state.srcH});
			 
			//加载zoomLevel = 1的所有图片
			for(i=1;i<=yuJsonConfig.count;++i){
				var key = state.id + '_' + state.zoomLevel + '_' + i;
				var src = state.path + "/"+state.serials[state.zoomLevel] + "_" + state.serials[i] + state.imgType;
				if(isIE){
					src+= "?t=" + Math.random();
				}
				state.processCount += 1;
				loadImg(key, src, function(img){
					state.processCount -= 1;
					showProcesser(state.count - state.processCount, state.count);
					var clock_str = 0;
					if(isIE){
						clock_str = img.src.replace(/^.*\/\w{2}_(\w{2})\.[^.]+\?.*$/g, "$1");
					}else{
						clock_str = img.src.replace(/^.*\/\w{2}_(\w{2})\.[^.]+$/g, "$1");
					}
					var clock = state.reserials[clock_str];
					//document.title = clock_str+":"+clock;\
					
					$(state.yuYCID + " .clockwise_1").append('<img src="' + img.src + '" id="clockwise_' + state.id + clock + '"/>');
					/**
					if(clock==1){
						//加载首张图片
						$(state.yuYCID + " .clockwise_1").attr("src", img.src);
					}
					**/
					if(state.clockwiseLevel < clock){
						yuZoomObj.turnTo(clock);	
					}
					if(state.processCount <= 0){
						hideProcesser(function(){
							//----------加载完图片后------------
							init_action();
							
							//显示缩放页面
							state.loaded = true;
							//加载完成后事件
							for(j = 0; j < state.onload.length; ++j){
								var fun = state.onload[j];
								fun();
							}
						});
					}
				});
			}
			
										   
		})
	};
	
	/**
	 * 初始化缩略图
	 */
	var init_thumb = function(){
		if(state.x>0 && state.y>0){
			//在框内，不需要缩略导航图
			$(state.yuYCID + " " + state.thumbsYClass).fadeOut();
			return;
		}
		//计算缩略图高、宽
		var w_r = state.srcW/state.yuW;
		var h_r = state.srcH/state.yuH;
		var h = 0, w = 0;
		if(w_r > h_r){
			//取高
			h = parseInt(state.yuH / state.thumbRate);
			if(h > state.maxThumbH){
				h = parseInt(state.maxThumbH);
			}
			w = parseInt(state.srcW * h / state.srcH);
		}else{
			//取宽
			w = parseInt(state.yuW / state.thumbRate);
			if(w > state.maxThumbW){
				w =parseInt( state.maxThumbW);
			}
			h = parseInt(state.srcH * w / state.srcW);
		}
		
		//保存缩略图高、宽
		state.thumbW = w;
		state.thumbH = h;
		
		var key = state.id + '_1_' + state.clockwiseLevel;
		var img = yuZoomImages.get(key);
		if(img == null)return;
		//判断位置
		
		$(state.yuYCID + " " + state.thumbsYClass).css({width:w,height:h}).fadeIn().find("img").attr("src",img.src).css({width:w,height:h});
		
		
		//设置可视范围框
		var r = Math.pow(2,state.zoomLevel-1);
		var rate_w = r * state.srcW / w;
		var rate_h = r * state.srcH / h;
		
		var x1 = -state.x / rate_w;
		var y1 = -state.y / rate_h;
		var w1 =  state.yuW / rate_w;
		var h1 =  state.yuH / rate_h;
		$(state.yuYCID + " " + state.thumbsYClass + " .guild").css({top:y1,left:x1,width:w1,height:h1});
	};
	
	//-----------------------------------------执行
	//当前对象
	var yuZoomObj = this;
	
	/**
	 * 初始化事件
	 */
	var init_action = function(){
		//加载工具菜单事件
		var tools_height = $(state.yuYCID + " " + state.yuZoomToolsYClass).height();
		var over_act = {bottom:0};
		var out_act = {bottom:-tools_height};
		var yuZoomToolsHandle = state.yuYCID + " " + state.yuZoomToolsYClass;
		switch(state.toolsPosition){
			case 'top':
				over_act = {top:0};
				out_act = {top:-tools_height};
				$(yuZoomToolsHandle).css(out_act);
				break;
			case 'left':
				over_act = {left:0};
				$(yuZoomToolsHandle).css({width:tools_height,height:state.yuH,left:-tools_height,bottom:'auto',top:0});
				out_act = {left:-tools_height};
				break;
			case 'right':
				over_act = {right:0};
				$(yuZoomToolsHandle).css({width:tools_height,height:state.yuH,left:'auto',bottom:'auto',top:0,right:-tools_height});
				out_act = {right:-tools_height};
				break;
			default:
				break;
		}
		$(state.yuYCID).hover(
			function(){
				$(yuZoomToolsHandle).dequeue().animate(over_act);
			},
			function(){
				$(yuZoomToolsHandle).dequeue().animate(out_act);
			}
		);
		
		$(state.yuYCID+" .yuZoomTools .handle_reset").click(function(){
			yuZoomObj.autoPlay({count:2});
		});

		$(state.yuYCID+" " + state.yuZoomToolsYClass + " .handle_move").click(function(){
			if(state.x<0 || state.y<0)
				yuZoomObj.setAction('move');
		});

		$(state.yuYCID+" " + state.yuZoomToolsYClass + " .handle_3d").click(function(){
			if(state.zoomLevel<=state.maxClockwiseZoom){
				yuZoomObj.setAction('3d');
			}
		});
		
		$(state.yuYCID+" " + state.yuZoomToolsYClass + " .handle_fullscreen").click(function(){
			yuZoomObj.fullScreen(); 
		});
		
		$(state.yuYCID + " " + state.yuZoomToolsYClass + " .handle_exitfullscreen,"+state.yuYCID+" .float_exitfullscreen").click(function(){
			yuZoomObj.resetScreen();
		});
		//ESC键事件
		$(document).keyup(function(e){
			if(e.which == 27){yuZoomObj.resetScreen();}
		}).mouseup(function(){
			if(state.ondrag){
				state.busy = false;
				state.ondrag = false;
				$(state.yuYCID + " .picsDiv").show();
				load_view_image();
			}
		});
		
		$(state.yuYCID + " .slider_content").hover(
			function(){state.slide = true},
			function(){state.slide = false}
		);
		
		
		/**
		$("#yuZoom_" + state.id + " .slider_content").mouseover(
			function(){
				
			this.releaseCapture();return;
				state.slide = true;
				state.slider = parseInt($(this).find(".slider").css('left'));
			}
		);
		*/
		
		//$(state.yuYCID + " " + state.thumbsYClass + " .guild").hover(function(){state.guild = true},function(){state.guild = false});
		
		//加载拖动事件
		$(state.yuYCID).mousedown(function(e){
			state.snapshot.x = e.pageX;
			state.snapshot.y = e.pageY;
			state.snapshot.clockwise = state.clockwiseLevel;
			state.snapshotAvailable = true;
			try{this.setCapture();}catch(e){}
		}).mouseup(function(e){
			state.snapshotAvailable = false;
			state.ondrag = true;
			state.busy = true;
			//if(state.slide)state.slide = false;
			try{
				this.releaseCapture();
			}catch(e){}
		}).mouseout(function(e){
			state.snapshotAvailable = false;
			try{
				this.releaseCapture();
			}catch(e){}
		}).mousemove(function(e){
			if(!state.snapshotAvailable)return;
			try{
				window.getSelection&&window.getSelection().removeAllRanges(); 
				document.selection&&document.selection.empty();
				this.releaseCapture();
			}catch(e){}
			var action = state.action;
			var mx =  e.pageX - state.snapshot.x;
			var my = e.pageY - state.snapshot.y;
			switch(action){
				case '3d':
					var clockwise = 0;
					var rate = state.yuW / state.count / 2;
						
					if(state.revert){
						clockwise = parseInt(-mx / rate) + state.snapshot.clockwise;
					}else{
						clockwise = parseInt(mx / rate) + state.snapshot.clockwise;
					}
					
					if(clockwise == 0){
						return;
					}
					//document.title = cl;
					state.ondrag = true;
					state.busy = true;
					$(state.yuYCID + " .picsDiv").hide(); 
					yuZoomObj.turnTo(getClockwise(clockwise));
					break;
				case 'move':
					var x = parseInt(mx);
					var y = parseInt(my);
					if(!state.ondrag)
						yuZoomObj.move(x,y);
					state.snapshot.x = e.pageX;
					state.snapshot.y = e.pageY;
					break;
			}
		});
		
		//加载滚轮事件
		$(state.yuYCID).on("mousewheel",function(e, delta){
			if(delta > 0){
				//向上滚动 ，放大
				if(state.zoomLevel == state.maxZoom)return false;
				yuZoomObj.zoomIn();
			}else{
				//向下滚动，缩小
				if(state.zoomLevel == 1)return false;
				yuZoomObj.zoomOut();
			}
			return false;
		})
		
		//初始化双击事件
		.dblclick(function(){
			try{
				window.getSelection&&window.getSelection().removeAllRanges(); 
				document.selection&&document.selection.empty();
			}catch(e){}
			if(state.zoomLevel == state.maxZoom){
				//缩小
				yuZoomObj.zoomOut();
			}else{
				yuZoomObj.zoomIn();
			}
			return false;
		});
		
		state.ondrag = false;
		//拖动滚动条
		$(state.yuYCID + " .slider").mousedown(function(){
			state.snapshotAvailable = false;
			state.ondrag = true;
			state.busy = true;
			$(state.yuYCID + " .picsDiv").hide();
			reset_view_image();//.find("img").attr("src",nullPic);
		}).mouseup(function(){
				state.busy = false;
				state.ondrag = false;
				$(state.yuYCID + " .picsDiv").show();
				load_view_image();
			
		}).draggable({
			drag : function(event, ui_){
				var rate = state.yuW / state.count / 2;
				var clockwise = parseInt(ui_.position.left / rate);
				if(state.revert){
					clockwise = state.count - clockwise;
				}
				yuZoomObj.turnTo(getClockwise(clockwise));
			},
			axis: 'x',
			containment : 'parent'
		});
		
		$(state.yuYCID + " .guild").draggable({
			containment : 'parent',
			start : function(event, ui_){
				state.guild = true;
				state.snapshotAvailable = false;
				state.snapshot.x = ui_.position.left;
				state.snapshot.y = ui_.position.top;
			},
			stop : function(){
				state.guild = false;
			},
			drag : function(event, ui_){
				var x = ui_.position.left - state.snapshot.x;
				var y = ui_.position.top - state.snapshot.y;
				yuZoomObj.move(x,y);
				state.snapshot.x = ui_.position.left;
				state.snapshot.y = ui_.position.top;
			}
		});
		
		
		
		$(state.yuYCID + " .zoomInBtn").click(function(){
			yuZoomObj.zoomIn();
		});
		
		$(state.yuYCID + " .zoomOutBtn").click(function(){
			yuZoomObj.zoomOut();
		});
	};
	var siteYuKey = yuZoomKey;
	
	/**
	 * 获取正确的值（如果错误的，会作纠正）
	 */
	var getClockwise = function(clockwise){
		var count = state.count;
		while(clockwise<=0){
			clockwise += count;
		}
		clockwise %= count;
		if(clockwise == 0){
			return count;
		}else{
			return clockwise;
		}
	};
	
	/**
	 * 内加载图片
	 */
	var loadImg = function(key,src,loadFun){
		if(loadFun==null)loadFun = function(){};
		if(src==null)
			src = state.path + "/"+state.serials[state.zoomLevel] + "_" + state.serials[state.clockwiseLevel] + state.imgType;			
		if(isIE){
			src+= "?t=" + Math.random();
		}
		
		var img = new Image();
		img.src = src;
		img.key = key;
		img.loadFun = loadFun;
		$(img).load(function(){
			yuZoomImages.put(this.key, this);
			if(this.loadFun){
				this.loadFun(this);
			}
		});
	};
	
	/**
	 * 显示进度条
	 * @param processed 已经处理进度
	 * @param total 总进度数 
	 */
	var showProcesser = function(processed, total){
		$(state.yuYCID + " .yuZoomProcesser span").width(209 * processed / total).show();
	};
	
	var hideProcesser = function(callbackFun){
		$(state.yuYCID + " .yuZoomProcesser").hide();
		if(callbackFun){
			callbackFun();
		}
	};
	
	/**
	 * 初始化
	 */
	var init = function(myOptions){
		var yuZoomContentVar = "yuZoomContent";
		state.thumbsClass = "yuZoomThumbs";
		state.thumbsYClass = ".yuZoomThumbs";
		state.yuZoomToolsClass = "yuZoomTools";
		state.yuZoomToolsYClass = ".yuZoomTools";
		if(myOptions == null){
			alert(language.null_configure);	
			return;
		}
		if(myOptions.content == null || $(myOptions.content).length != 1){
			alert(language.yuContentNull);
			return;
		}else{
			state.content = myOptions.content;
		}
		
		//加载配置文件
		if(myOptions.configUrl == null){
			alert(language.yuConfigureUrlNull);
			return;
		}else{
			state.configUrl = myOptions.configUrl;
		}
			
		if(myOptions.toolsPosition){
			state.toolsPosition = myOptions.toolsPosition;
		}
		
		//初始化组件高、宽
		if(myOptions.yuW && myOptions.yuW>0){
			state.yuW = myOptions.yuW;
		}else{
			state.yuW = $(state.content).width();
		}
		if(myOptions.yuH && myOptions.yuH>0){
			state.yuH = myOptions.yuH;
		}else{
			state.yuH = $(state.content).height();
		}
		 
		state.id = (Math.random() + "").substr(3,7);
		state.yuCID = 'yuZoom_' + state.id;
		state.yuYCID = '#yuZoom_' + state.id;
		if(!$(state.yuYCID).length){
			//生成应用框架
			var content = $('<div class="'+yuZoomContentVar+'" id="' + state.yuCID + '"><div class="'+state.yuZoomToolsClass+'"><div class="slider_content"><div class="slider"><span></span></div></div></div><div class="'+state.thumbsClass+'"><div class="guild"><span></span></div><img src="'+nullPic+'"/></div><div class="yuZoomProcesser"><span></span></div><div class="clockwise_1"></div><div class="mb"></div><div class="picsDiv"></div><div class="zoomDiv"><a href="javascript:void(0)" class="zoomInBtn"></a><div class="zoomKD"><span></span></div><a href="javascript:void(0)" class="zoomOutBtn"></a></div><a class="icon handle_exitfullscreen float_exitfullscreen"></a></div>');
			$(content).css({'background-color':state.background,width:state.yuW,height:state.yuH})
				.find(".yuZoomProcesser").css({left:(state.yuW - 209) / 2});
			$(content).find(".mb").css({width:state.yuW,height:state.yuH});
			
			//初始化工具栏
			$(content).find(state.yuZoomToolsYClass).append(
				'<a href="javascript:void(0)" class="icon handle_3d selected" title="'+language.shift_3d+'"></a>'+
				'<a href="javascript:void(0)" class="icon handle_move" title="'+language.menu_move+'"></a>'+
				'<a href="javascript:void(0)" class="icon handle_zoom" title="'+language.menu_zoom+'"></a>'+
				'<a href="javascript:void(0)" class="icon handle_reset" title="'+language.menu_rotate+'"></a>'+
				'<a href="http:/'+'/www.duoec.com/help.html" target="_blank" class="icon handle_help" title="'+language.menu_help+'"></a>'+
				'<a href="javascript:void(0)" class="icon handle_detail" title="'+language.menu_detail+'"></a>'+
				'<a href="javascript:void(0)" class="icon handle_fullscreen" title="'+language.menu_fullScreem+'"></a>'+
				'<a href="javascript:void(0)" class="icon handle_exitfullscreen" title="'+language.menu_exitfullScreem+'"></a>');
			
			$(state.content).append(content);
			
		}
		loadConfig(function(){
			showProcesser();
		});
	};
	init(option);
};

var YuZoom = MyYuZoom;